#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
using i128 = __int128;
const int N = 1e6 + 5;

void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    vector<int> check(n + 1, 0);  // 记录当前位置后面有没有更大的数
    for (int i = n - 1; i >= 0; i--) {
        check[i] = max(check[i + 1], a[i]);
    }
    stack<int> st;
    vector<int> ans;
    for (int i = 0; i < n; i++) {
        st.push(a[i]);
        while (!st.empty() && st.top() > check[i + 1]) {
            ans.push_back(st.top());
            st.pop();
        }
    }
    for (int i = 0; i < ans.size(); i++) {
        if (i) cout << " ";
        cout << ans[i];
    }
    cout << endl;
    return;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    solve();

    return 0;
}